#!/usr/bin/env python2
##usr/local/bin python2
import os
import binascii
import sys
import re

## internet address: https://www.jianshu.com/p/11d48d7017c6
## internet address: www.ip33.com/crc.html
## crc type : CRC-8/MAXIM ==> x8+x5+x4+1 
## For Example Input Data = [01,18,00] ==>crc8 = 0xd6
def crc_1byte(data):
  crc_1byte = 0
  for i in range(0,8):
    if((crc_1byte^data)&0x1):
      crc_1byte^=0x18
      crc_1byte>>=1
      crc_1byte|=0x80
    else:
      crc_1byte>>=1
    data>>=1
    print ("num:%d crc1Byte:%s din:%d "%(i,hex(crc_1byte),data)) 
  return crc_1byte

def crc_byte(data):
  ret = 0
  for byte in data:
    ret = (crc_1byte(ret^byte))
  return ret

if __name__=="__main__":
  ## a = [1,18,0]#### shoule be dec, result should be "0xd6"
  ## result=hex(crc_byte(a))
  ## print(result)
#### get the parameter for external 
  print(sys.argv[0]) ##crc8.py
  print(sys.argv[1]) ##cmd 1
  inFile = sys.argv[1]
  fi = open(inFile,"r")
  lstIn = fi.readlines()
  fi.close()
#### process
  for i in range (0,len(lstIn)):

    ilstChars = re.findall(r'.{2}',lstIn[i])
    lstNums = [ int(x,16) for x in ilstChars ]
    crcData = crc_byte(lstNums)
    print(hex(crcData))


